import Koa from 'koa';
import http from 'http'
import convert from 'koa-convert'
import cors from 'koa-cors' //跨域
import bodyParser from 'koa-bodyparser' //请求体JSON解析
import onerror from 'koa-onerror' //错误处理
import resource from 'koa-static' //静态资源托管

import path from 'path';

import MyLogger from './middlewares/logger';
import ResponseFormatter from './middlewares/response_formatter';
import routes from './routes';
import config from './config';

const app = new Koa();

onerror(app)

app.use(convert(cors()))

app.use(bodyParser())

app.use(convert(resource(path.join(__dirname, 'public'))))

// logger日志文件输出
app.use(MyLogger);
// api输出格式化
// 必须在router之前
app.use(ResponseFormatter('^/api'));

// routes
app.use(routes.routes(), routes.allowedMethods());

app.on('error', (error, ctx) => {
    // 所有未捕获的错误
    console.log('server error :')
    console.log(error)
})

http.createServer(app.callback()).listen(config.port).on('listening', function () {
    console.log('正在监听端口：' + config.port)
})

export default app;
